'use client'

import { useEffect, useRef, useState } from 'react'
import { motion, useAnimation, animate } from 'framer-motion'

interface StatItemProps {
  value: number
  suffix?: string
  title: string
}

const StatItem = ({ value, suffix = '+', title }: StatItemProps) => {
  const [isInView, setIsInView] = useState(false)
  const ref = useRef(null)
  const [displayValue, setDisplayValue] = useState(0)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsInView(true)
        }
      },
      {
        threshold: 0.5,
      }
    )

    if (ref.current) {
      observer.observe(ref.current)
    }

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current)
      }
    }
  }, [])

  useEffect(() => {
    if (isInView) {
      const controls = animate(0, value, {
        duration: 1.5,
        onUpdate(value) {
          setDisplayValue(Math.floor(value))
        },
        ease: 'easeOut',
      })

      return controls.stop
    }
  }, [isInView, value])

  return (
    <div ref={ref} className="text-center">
      <div className="text-4xl font-bold text-green-600 mb-2">
        {displayValue}
        {suffix}
      </div>
      <div className="text-gray-600">{title}</div>
    </div>
  )
}

export default function CompanyStats() {
  const stats = [
    { value: 21, title: '行业解决方案经验' },
    { value: 50000, title: '月销量' },
    { value: 1000, title: '客户案例' },
    { value: 5000, title: '厂房面积' },
  ]

  return (
    <section className="py-16 bg-white">
      <div className="container mx-auto px-4">
        <h2 className="text-3xl font-bold text-center mb-12 text-green-600">企业实力</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
          {stats.map((stat, index) => (
            <StatItem key={index} {...stat} />
          ))}
        </div>
      </div>
    </section>
  )
}
